//首页
import React, { useEffect, useRef, useState } from 'react';
import { View, Text, Image } from '@tarojs/components';
import { observer } from 'mobx-react-lite';
import './index.less';
import TitleBar from 'src/components/titleBar';
import Taro, { useDidShow, usePageScroll } from '@tarojs/taro';
import CommonPopup from '@/src/components/commonPopup';
import { AtSearchBar, AtTabs, AtTabsPane } from 'taro-ui';
import store from '../../store';
import CommentItem from '@/src/components/commentItem';
import ArticleItem from '@/src/components/articleItem';
import BottomContainer from '@/src/components/bottomContainer';
import { getConversionFun, isLoginFun } from '@/src/common/method/commonFun';
import {
  recommendListFun,
  shopCigarCabinetFun,
} from '@/src/common/method/homeFun';
import InfiniteScroll from '@/src/components/infiniteScroll';
import videoIcon from '../../assert/imgs/vedio/videoIcon.png';
import VedioItem from '@/src/components/vedioItem';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { userInfoFun } from '@/src/common/method/loginFun';
import { updateInfoFun } from '@/src/common/method/userInfoFun';
const Home = () => {
  const [currentTab, setCurrentTab] = useState(0);
  const [showPopup, setShowPopup] = useState<boolean>(false);
  const [value, setValue] = useState('');
  const [clickAble, setClickAble] = useState<boolean>(true); //是否可点击状态
  const [dataList, setDataList] = useState<any>([]); //首页列表
  const [loadingText, setLoadingText] = useState<any>('加载中');
  // const tabList: any = [{ title: '推荐' }, { title: '商城' }];
  const tabList: any = [{ title: '推荐' }];
  const [minContentDynamicId, setMinContentDynamicId] = useState<any>(''); //最小内容id-动态
  const [minContentArticleId, setMinContentArticleId] = useState<any>(''); //最小内容id-文章
  const [minContentVideoId, setMinContentVideoId] = useState<any>(''); //最小内容id-视频
  const [hasMoreDynamicDown, setHasMoreDynamicDown] = useState<any>(''); //最大内容id-动态
  const [hasMoreArticleDown, setHasMoreArticleDown] = useState<any>(''); //最大内容id-文章

  const [hasMoreVideoDown, setHasMoreVideoDown] = useState<any>(''); //最大内容id-视频
  const [scrollDirection, setScrollDirection] = useState<any>('DOWN'); //滚动方向
  const [hasMore, setHasMore] = useState<boolean>(false); //是否还有更多
  const [homeScrollTop, setHomeScrollTop] = useState<number | undefined>(
    undefined
  );
  const latestScrollTopRef = useRef(0);

  // 一级下拉刷新状态
  const [refresherTriggered, setRefresherTriggered] = useState(false);
  const lastScrollTop = useRef(0); // 使用ref记录上一次滚动位置
  // 发布按钮
  const gotoDraftBox = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    store.commonStore.setShowTabBar(false);
    setShowPopup(true);
  };
  // 附近门店
  const gotoNearbyStore = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    Taro.navigateTo({
      url: '/subPagesAccount/nearbyStores/index',
    });
  };
  // 活动
  const gotoActivity = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (!isLoginFun()) return;
    Taro.navigateTo({
      url: '/subPagesActivity/home/index',
    });
  };
  const gotoPublish = (type: string) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (type === 'comment') {
      //发动态
      Taro.navigateTo({
        url: '/subPagesAccount/publishComment/index',
      });
    } else if (type === 'article') {
      //发文章
      Taro.navigateTo({
        url: '/subPagesAccount/publishArticle/index',
      });
    } else if (type === 'vedio') {
      //发视频
      Taro.navigateTo({
        url: '/subPagesAccount/publishVedio/index',
      });
    }
    // 关闭弹窗
    setShowPopup(false);
  };

  const content = () => {
    return (
      <View className="publish-modal-container">
        <View className="publish-title"></View>
        <View
          className="publish-contents"
          onClick={() => gotoPublish('comment')}
        >
          <View className="content-header">发动态</View>
          <View className="content-container">分享这一刻的快乐...</View>
          <View className="content-footer">
            <Image
              src="https://file.linkcook.cn/image/wineMiniProgram/home/addPic.png"
              className="addPic"
            ></Image>
            <Text>添加图片</Text>
          </View>
        </View>
        <View className="publish-buttons">
          <View onClick={() => gotoPublish('comment')}>
            <View className="button-container">
              <Image
                src="https://file.linkcook.cn/image/wineMiniProgram/home/comment.png"
                className="bt-icon"
              ></Image>
            </View>
            <View className="bt-desc">发动态</View>
          </View>
          <View onClick={() => gotoPublish('article')}>
            <View className="button-container">
              <Image
                src="https://file.linkcook.cn/image/wineMiniProgram/home/article.png"
                className="bt-icon-article"
              ></Image>
            </View>
            <View className="bt-desc">发文章</View>
          </View>
          <View onClick={() => gotoPublish('vedio')}>
            <View className="button-container">
              <Image src={videoIcon} className="bt-icon-video"></Image>
            </View>
            <View className="bt-desc">发视频</View>
          </View>
        </View>
      </View>
    );
  };

  // 更新用户位置信息
  const updateUserLocation = async (province: string) => {
    // 更新用户省份信息
    const resq: any = await userInfoFun({
      access_token: store.commonStore.accessToken?store.commonStore.accessToken:Taro.getStorageSync('access_token_login'),
    });
    try {
      await updateInfoFun({
        ucUserId: resq.userId,
        ucLoginPhone: resq.mobile,
        ucNickname: Taro.getStorageSync(`nickname-${resq.userId}`),
        ucAvatarUrl: resq.avatarUrl,
        address: province, // 你要的省份
      });
    } catch {}
  };

  // 获取用户定位权限
  const getLocationAuth = () => {
    // 获取用户定位权限
    Taro.getLocation({ type: 'gcj02' })
      .then((loc: any) => {
        const location = `${loc.latitude},${loc.longitude}`;
        // 成功授权，使用真实位置
        getConversionFun(location)
          .then(async (res: any) => {
            store.commonStore.setCity(res.city.areaName);
            store.commonStore.setCityCode(res.city.areaCode);
            store.commonStore.setProvinceCode(res.province.areaCode);
            store.commonStore.setProvince(res.province.areaName);
            updateUserLocation(res.province.areaName);
          })
          .catch((err: any) => {
            console.log(err, 'err11111');
          });
      })
      .catch(() => {
        // 用户未授权，保持 DEFAULT_LOC（天安门）
        console.warn('定位未授权');
        store.commonStore.setProvinceCode('');
        store.commonStore.setProvince('');
        updateUserLocation('未知');
      });
  };
  //查询用户推荐内容
  const queryRecommendList = (flag: boolean) => {
    recommendListFun({
      scrollDirection: scrollDirection,
      pageNum: 1,
      pageSize: 10,
      downRequest: {
        minContentDynamicId: flag ? null : minContentDynamicId,
        minContentArticleId: flag ? null : minContentArticleId,
        minContentVideoId: flag ? null : minContentVideoId,
        hasMoreDynamicDown: flag ? true : hasMoreDynamicDown,
        hasMoreArticleDown: flag ? true : hasMoreArticleDown,
        hasMoreVideoDown: flag ? true : hasMoreVideoDown,
      },
    }).then((res: any) => {
      console.log(res, '首页推荐内容====');
      setMinContentDynamicId(res.contentRecommendDownVo.minContentDynamicId);

      setMinContentArticleId(res.contentRecommendDownVo.minContentArticleId);
      setMinContentVideoId(res.contentRecommendDownVo.minContentVideoId);

      setHasMoreDynamicDown(res.contentRecommendDownVo.hasMoreDynamicDown);

      setHasMoreArticleDown(res.contentRecommendDownVo.hasMoreArticleDown);
      setHasMoreDynamicDown(res.contentRecommendDownVo.hasMoreDynamicDown);

      setHasMoreVideoDown(res.contentRecommendDownVo.hasMoreVideoDown);
      setLoadingText('');
      if (flag) {
        // 下拉刷新 / 首次进来：直接重置列表
        setDataList(res.contentRecommendVos || []);
      } else {
        // 上拉加载更多：在原列表后面拼接
        setDataList((prev: any) =>
          (prev || []).concat(res.contentRecommendVos || [])
        );
      }
      if (res.contentRecommendVos.length > 0) {
        setHasMore(true);
      } else {
        setHasMore(false);
      }
    });
  };
  const firstShowRef = useRef(true); // 标记是否是本次会话的首次展示
  useDidShow(() => {
    Taro.onNetworkStatusChange(getNetWorkStatus);
    Taro.getNetworkType()
      .then(() => store.commonStore.setNetworkStatus(true))
      .catch(() => store.commonStore.setNetworkStatus(false));

    // 从详情返回：只恢复位置，不做任何请求
    const fromDetail =
      Number(Taro.getStorageSync('fromHomeToDetail') || 0) === 1;
    if (fromDetail) {
      const savedTop = Number(Taro.getStorageSync('homeScrollTop') || 0);
      setHomeScrollTop(savedTop + 1);
      Taro.nextTick(() => setHomeScrollTop(savedTop));
      // 用完清掉标记，避免下一次误判
      Taro.setStorageSync('fromHomeToDetail', 0);
      return; // 直接 return，别触发刷新！
    }

    // 冷启动 / 真正的首次进入首页：做初始化拉取
    if (firstShowRef.current) {
      firstShowRef.current = false;
      queryRecommendList(true);
      store.commonStore.setActiveTab(0);
    }
  });

  const shopCigarCabinet = () => {
    const data = {
      pageType: 'SHOP_PAGE',
    };
    shopCigarCabinetFun(data)
      .then((res: any) => {
        store.commonStore.setPagePath(res.pagePath);
      })
      .catch(() => {});
  };

  useEffect(() => {
    //获取用户定位权限
    getLocationAuth();
    //查询商城半屏跳转地址的方法
    shopCigarCabinet();
  }, []);
  usePageScroll((res: any) => {
    const currentScrollTop = res.scrollTop;
    if (currentScrollTop > lastScrollTop.current) {
      console.log('向下滑动');
      //如果滑动到
      setScrollDirection('DOWN');

      // 执行下滑操作
    } else if (currentScrollTop < lastScrollTop.current) {
      console.log('向上滑动');
      // 执行上滑操作
      setScrollDirection('UP');
    }

    // 更新滚动位置
    lastScrollTop.current = currentScrollTop;
  });

  const onChange = (value: any) => {
    setValue(value);
  };
  const handleClick = async (value: any) => {
    setCurrentTab(value);
  };
  //跳转到文章详情
  const gotoDetail = (item: any, name: string) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo + '内容', icon: 'none' });
      return;
    }
    Taro.setStorageSync('fromHomeToDetail', 1);
    // 保存当前位置，供返回时恢复
    Taro.setStorageSync('homeScrollTop', latestScrollTopRef.current);
    if (clickAble) {
      if (name === 'userCenter') {
        Taro.navigateTo({
          url: `/subPagesAccount/userCenter/index?contentKind=${item.contentKind}&&contentType=${item.contentType}&&userId=${item.userInfoVo.ucUserId}`,
        });
      } else if (name === 'comment') {
        Taro.navigateTo({
          url: `/subPagesAccount/commentDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      } else if (name === 'article') {
        Taro.navigateTo({
          url: `/subPagesAccount/articleDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      } else {
        //跳转到视频详情
        Taro.navigateTo({
          url: `/subPagesAccount/vedioDetail/index?contentId=${item.contentId}&&contentKind=${item.contentKind}&&contentType=${item.contentType}`,
        });
      }
    }
  };

  //跳转到搜索页面
  const gotoSearch = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (clickAble) {
      Taro.navigateTo({ url: '/subPagesAccount/homeSearch/index' });
      setClickAble(false);
    }
    setTimeout(() => {
      setClickAble(true);
    }, 1000);
  };
  //首页内容列表
  const contentList = () => {
    return (
      <View>
        {dataList &&
          dataList.map((item: any, index: any) => {
            return (
              <View key={`${item.contentType}-${index}`}>
                {item.contentType === 'DYNAMIC' && (
                  <CommentItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    data={item}
                    home={true}
                    mine={false}
                  />
                )}
                {item.contentType === 'ARTICLE' && (
                  <ArticleItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    home={true}
                    mine={false}
                    data={item}
                  />
                )}
                {item.contentType === 'VIDEO' && (
                  <VedioItem
                    gotoDetail={(item: any, name: any) =>
                      gotoDetail(item, name)
                    }
                    mine={false}
                    home={true}
                    data={item}
                  />
                )}
              </View>
            );
          })}
      </View>
    );
  };
  //下拉查询数据
  const onEndReached = () => {
    if (loadingText === '加载中') {
      return false;
    }
    setLoadingText('加载中...');
    return queryRecommendList(false);
  };
  //加载下一页
  const loadMore = () => {
    let val: any = false;
    if (loadingText === '' && onEndReached) {
      setLoadingText('加载中...');
      val = onEndReached();
    }
  };
  // 一级下拉刷新处理
  const handleRefreshFun = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('');
    setHomeScrollTop(undefined);
    setLoadingText('加载中...');
    setRefresherTriggered(true);
    //是否是首次下拉刷新
    queryRecommendList(true);
    setTimeout(() => {
      setRefresherTriggered(false);
    }, 1000);
  };

  return (
    <View
      className="home-container"
      style={{ paddingTop: `${store.commonStore.safeAreaTop}rpx` }}
    >
      <TitleBar showLeftBack={false} title=""></TitleBar>
      <View></View>
      <AtTabs
        current={currentTab}
        swipeable={false}
        tabList={tabList}
        className="home-tab"
        onClick={handleClick}
      >
        <AtTabsPane current={currentTab} index={0}>
          <View>
            <View className="search-container">
              <View
                className="search-container-AtSearchBar"
                onClick={gotoSearch}
              >
                <AtSearchBar
                  placeholder="搜索"
                  className="custom-search-bar"
                  value={value}
                  showActionButton={true}
                  // onFocus={() => gotoSearch()}
                  onChange={() => onChange(value)}
                  disabled // 禁用输入，确保只能点击跳转
                />
              </View>
              <View className="home-entrance">
                <Image
                  className="entrance-icon"
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/huodong.png"
                  onClick={gotoActivity}
                />
                <Image
                  className="entrance-icon"
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/fujin.png"
                  onClick={gotoNearbyStore}
                />
                <Image
                  className="entrance-icon"
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/fabu.png"
                  onClick={gotoDraftBox}
                />
              </View>
            </View>
            <View
              className="home-content"
              style={{
                height: `calc(100vh - (112rpx + ${store.commonStore.pageAreaTop}rpx + ${store.commonStore.safeAreaBottom}rpx + 118rpx))`,
                paddingBottom: `calc(${store.commonStore.safeAreaBottom}rpx + 112rpx)`,
              }}
            >
              <InfiniteScroll
                hasMore={hasMore}
                loadMore={() => loadMore()}
                refresherTriggered={refresherTriggered}
                dataList={dataList}
                handleRefresh={() => handleRefreshFun()}
                loading={loadingText === '' ? false : true}
                content={contentList()}
                /** 受控恢复位置 & 回传保存 */
                scrollTop={homeScrollTop}
                onScrollTopChange={(top) => {
                  latestScrollTopRef.current = top;
                  // 也可以节流后再写入 storage
                }}
              />
            </View>
            <BottomContainer />
          </View>
        </AtTabsPane>
        <AtTabsPane current={currentTab} index={1}>
          <View>标签页二的内容</View>
        </AtTabsPane>
      </AtTabs>
      {/* 文章UI内容 */}
      <CommonPopup
        visible={showPopup}
        onClose={() => {
          setShowPopup(false);
          store.commonStore.setShowTabBar(true);
        }}
        className="homePopupClass"
        full={true}
        content={content()}
      ></CommonPopup>
    </View>
  );
};

export default observer(Home);
